package br.ufmg.ubicomp.droidguide.communication;

import java.io.IOException;
import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;

import br.ufmg.ubicomp.droidguide.context.Weather;

public class WeatherCommunicationService {
	
	public static final String BASE_URL = "http://droidguide.appspot.com/context/weather/read?";
			
	public static Weather getWeather(String latitude, String longitude) throws Exception, IOException {		
		String url = BASE_URL + "latitude=" + latitude + "&longitude=" + longitude;
		String temperature, pressure, humidity;
		
		temperature = pressure = humidity = "";
		
//		/* Make request */
//		DefaultHttpClient client = new DefaultHttpClient();
//		HttpGet method = new HttpGet(url);		
//		HttpResponse response =  client.execute(method);
//		HttpEntity entity = response.getEntity();
//		InputStream inStream = entity.getContent();
//		
//		/* Parse XML */
//		
//		DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
//		Document doc = docBuilder.parse(inStream);
//		// root element.
//		Element root = doc.getDocumentElement();		
//		NodeList children = root.getChildNodes();
		NodeList children = HttpRequestProcessor.processRequest("JAVA_NET", url);
				
		
		for (int i = 0; i < children.getLength(); i++) {
			Node child = children.item(i);
			
			if (child instanceof Element) {
				Element childElement = (Element) child;
				Text textNode = (Text) childElement.getFirstChild();
				String text = textNode.getData().trim();
				if (childElement.getTagName().equals("temperature")) {
					temperature = text;
				} else if (childElement.getTagName().equals("rain")) {
					pressure = text;
				} else if (childElement.getTagName().equals("humidity")) {
					humidity = text;
				}
			}
		}
		
		return new Weather(temperature, pressure, humidity);
	}

}
